package view;

import com.sun.lwuit.Form;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import core.RegionsFilter;
import core.RegionsFilter.Pair;
import view.additional.CheckBoxListRenderer;
import view.additional.ThumbList;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Kvest
 */
public class RegionsFilterForm extends Form implements ActionListener
{
    private static final int SET_ID = 1;
    private static final int BACK_ID = 2;
    private static final int SELECT_ALL_ID = 3;
    private static final int UNSELECT_ALL_ID = 4;

    private FilterUpdate listener;
    private Command set;
    private Command selectAll;
    private Command unselectAll;
    private Command back;

    private RegionsFilter filter;
    private ThumbList regionsList;

    public RegionsFilterForm(RegionsFilter filter)
    {
        super("Фильтр");

        this.filter = filter;
        listener = null;

        init();
    }

    private void init()
    {
        setLayout(new BorderLayout());
        setScrollable(false);

        addCommandListener(this);

        back= new Command("Назад", BACK_ID);
        addCommand(back);

        unselectAll = new Command("Снять все",UNSELECT_ALL_ID);
        addCommand(unselectAll);

        selectAll = new Command("Выбрать все",SELECT_ALL_ID);
        addCommand(selectAll);

        set = new Command("Применить", SET_ID);
        addCommand(set);

        //Создаем и настраиваем список
        regionsList = new ThumbList();
        regionsList.setSelectCommandText("");
        regionsList.setFixedSelection(ThumbList.FIXED_NONE_CYCLIC);
        CheckBoxListRenderer render = new CheckBoxListRenderer();
        render.getStyle().setPadding(Component.BOTTOM, 0);
        render.getStyle().setPadding(Component.TOP, 0);
        regionsList.setRenderer(render);
        regionsList.getStyle().setPadding(Component.BOTTOM, 0);
        regionsList.getStyle().setPadding(Component.TOP, 0);
        regionsList.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                RegionsFilter.Pair selectedItem = (RegionsFilter.Pair)regionsList.getSelectedItem();
                if (selectedItem != null)
                {
                    selectedItem.setActive(!selectedItem.isActive());
                }
            }
        });
        addComponent(BorderLayout.CENTER,regionsList);

        //Обновляем регионы
        update();
    }

    public void setListener(FilterUpdate listener)
    {
        this.listener = listener;
    }

    public void actionPerformed(ActionEvent evt)
    {
        Command cmd = evt.getCommand();
        if (cmd.getId() == SET_ID)
        {
            //Сохраняем фильтр
            saveFilter();

            if (listener != null)
            {
                String saveStr = filter.getString(false);
                listener.updateFilterAction(saveStr);
            }
        }
        else if (cmd.getId() == SELECT_ALL_ID)
        {
            doSelect(true);
        }
        else if (cmd.getId() == UNSELECT_ALL_ID)
        {
            doSelect(false);
        }
        else if (cmd.getId() == BACK_ID)
        {
            //Сбрасываем действия пользователя
            update();

            //Возвращаемся в меню
            if (listener != null)
            {
                listener.updateFilterBack();
            }
        }
    }

    private void doSelect(boolean value)
    {
        for (int i = 0; i < regionsList.getModel().getSize(); ++i)
        {
            ((RegionsFilter.Pair)regionsList.getModel().getItemAt(i)).setActive(value);
        }
    }

    public String getString()
    {
        return filter.getString(false);
    }

    public void selectAll()
    {
        doSelect(true);
        saveFilter();
    }

    private void saveFilter()
    {
        String nameTMP;
        boolean activeTMP;
        for (int i = 0; i < regionsList.getModel().getSize(); ++i)
        {
            nameTMP = ((RegionsFilter.Pair)regionsList.getModel().getItemAt(i)).getName();
            activeTMP = ((RegionsFilter.Pair)regionsList.getModel().getItemAt(i)).isActive();

            filter.setActive(nameTMP, activeTMP);
        }
    }

    public void show()
    {        
        super.show();
    }

    public void update()
    {
        if (filter == null)
        {
            return;
        }

        //Чистим форму
        while (regionsList.getModel().getSize() > 0)
        {
            regionsList.getModel().removeItem(0);
        }

        //Записываем новые значения
        Pair[] regList = filter.getRegionsList();
        for (int i = 0; i < regList.length; ++i)
        {
            //Добавляем в список копии(!!!!) объектов
            regionsList.getModel().addItem(regList[i].copy());
        }
    }

    public interface FilterUpdate
    {
        public abstract void updateFilterAction(String filterStr);
        public abstract void updateFilterBack();
    }
}
